package com.medistat.controllers;


import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.medistat.helpers.UrlConsts;
import com.medistat.services.UserContext;

@Controller("loginController")
@SessionScoped
public class LoginController implements Serializable{

	private static final long serialVersionUID = -8835308784811450758L;
	
	private String username;
	private String password;
	
	private UserContext userContext;

	@PostConstruct
	public void initialize() {
	}

	@Autowired
	public void setUserContext(UserContext userContext) {
		this.userContext = userContext;
	}

	
	public void login () {
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		RequestDispatcher requestDispatcher = ((ServletRequest)context.getRequest()).getRequestDispatcher("/login");
		try {
			requestDispatcher.forward((ServletRequest)context.getRequest(), (ServletResponse)context.getResponse());
		} catch (ServletException e) {
		} catch (IOException e) {
		}

		FacesContext.getCurrentInstance().responseComplete();
	}
	
	public String logout() {
		SecurityContextHolder.getContext().setAuthentication(null);
		userContext.setCredentials(null);
		return UrlConsts.DEFAULT_PAGE;
	}
	
	public void reset(){
		setUsername("");
		setPassword("");
	}
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}
